
// config 替换成自己的存储桶和数据中心信息
var config = {
    bucket: '',
    region: '',
    AK: '',
    SK: '',
};
// 需要接收配置参数
var ks3 = new KS3(config);

var util = {
    //创建指定大小的文件
    createFile: function (options) {
        var buffer = new ArrayBuffer(options.size || 0);
        var arr = new Uint8Array(buffer);
        [].forEach.call(arr, function (char, i) {
            arr[i] = 0;
        });
        var opt = {};
        options.type && (opt.type = options.type);
        var blob = new Blob([buffer], options);
        return blob;
    },
    // 选本地文件
    selectLocalFile: function (onChange) {
        var id = 'file_selector';
        var input = document.createElement('input');
        input.style = 'width:0;height:0;border:0;margin:0;padding:0;';
        input.type = 'file';
        input.id = id;
        input.onchange = function (e) {
            var files = this.files;
            if (!files.length) return;
            onChange && onChange(files);
            document.body.removeChild(input);
        };
        document.body.appendChild(input);
        input.click();
    },
};

// 页面初始化
initPage();
// 打印result
function logResult(params){
    var args = [].map.call(arguments, function (v) {
        return typeof v === 'object' ? JSON.stringify(v, null, 2) : v;
    });
    var text = args.join(' ');
    var resultDiv = document.querySelector('.result');
    var div = document.createElement('div');
    div.innerText = text;
    resultDiv.appendChild(div);
    resultDiv.scrollTop = resultDiv.scrollHeight;
}
//列举文件列表
function listObjects(){
    ks3.listObjects({
        'delimiter':'/',
        'max-keys': '500',
    }).then(res => {
        console.log(res);
        logResult('listObjects:', res);
    });
}
//获取object元数据
function headObject(){
    ks3.headObject({
        'key': '页面1-5.png'
    }).then(res => {
        console.log(res);
        logResult('headObject:', res);
    });
}
//获取object
function getObject(){
    ks3.getObject({
        'key': 'demo',
        headers: {
            Range: 'bytes=0-4'
        }
    }).then(res => {
        console.log(res);
        logResult('getObject:', res);
    });
}

function getObjectUrl(){
    ks3.getObjectUrl({
        'key': 'IMG_7DBACC50C65A-1.jpeg',
        'expires': 5*60,
        'method': 'DELETE',
        'Content-length' : 0,
    }).then(res => {
        console.log(res);
        logResult('getObjectUrl:', res);
    });
}
//删除目标对象
function delObject(){
    ks3.delObject({
        'key': '管控平台.png'
    }).then(res => {
        logResult('delObject:', res);
    });
}

//解冻
function restoreObject(){
    ks3.restoreObject({
        'key': '管控平台.png'
    }).then(res => {
        console.log(res);
        logResult('restoreObject:', res);
    });
}

//上传文件
function putObject(){
    let filename = 'testPutObject.zip';
    var blob = util.createFile({size: 1024 * 1024 * 1});
    ks3.putObject({
        'key': filename,
        // 'file': blob,
        encryption: true,
        'progress': function(e1,e2){
            logResult(e1)
        }
    }).then(res => {
        console.log(res);
        logResult('putObject res:', res);
    })
}

//追加上传
function appendObject(){
    let filename = 'testjs.zip';
    var blob = util.createFile({size: 1024 * 1024 * 1});
    ks3.appendObject({
        'key': filename,
        'file': blob,
        'progress': function(e1,e2){
            logResult(e1)
        },
        position: 0,
        encryption: true
    }).then(res => {
        console.log(res);
        logResult('appendObject res:', res);
    })
}


// 分块上传
function uploadMultiPart(){
    util.selectLocalFile(function(file){
        console.log('file:', file);
        var file = file[0];
        console.log(file)
        ks3.uploadMultiPart({
            key: file.name,
            file: file,
            encryption: true
        }, function(res){
            console.log(res)
            logResult('uploadMultiPart:', res);
        })
    })
}

// 查看已上传的分块
function listParts(){
    ks3.listParts({
        uploadId: '9156245afd564d6395d488c26b8d517d',
        key: '57M-copy.pdf'
    }).then(res => {
        console.log(res)
        logResult('listParts:', res);
    });
}

// 取消已上传块
function abortMultipartUpload(){
    ks3.abortMultipartUpload({
        uploadId: '9156245afd564d6395d488c26b8d517d',
        key: 'ToDesk_4.0.1.0.zip'
    }).then(res=> {
        logResult('abortMultipartUpload:', res);
    })
}

// 查询正在进行的分块上传
function listMultipartUploads(){
    ks3.listMultipartUploads({}).then(res => {
        logResult('listMultipartUploads:', res);
    })
}

// 查询object下的正在上传的分块
function getObjectPartUploads(){
    ks3.getObjectPartUploads({
        key: '/'
    }, function(err, data){
        logResult('getObjectPartUploads', err || data);
    })
}

// copy 小文件复制
function putObjectCopy(){
    ks3.putObjectCopy({
        key: 'index.html',
        sourceBucket: 'zwy-test',
        sourceKey: 'demo.txt',
        encryption: true,
        headers: {
            'content-type': ''
        }
    }).then(res => {
        logResult('putObjectCopy:', res);

    })
}

// copy 大文件复制
function uploadPartCopy(){
    ks3.uploadPartCopy({
        key: 'indexdemo.txt',
        // sourceBucket: 'wyr123',
        sourceBucket: 'zwy-test',
        sourceKey: '57M.pdf',
        // sourceKey: 'demo.txt',
        // encryption: true,
        headers: {
            'content-type': 'kjnsj'
        }
    }, function(res){
        console.log(res)
    })
}

// 修改存储类型
function modifyStorageClass(){
    ks3.modifyStorageClass({
        storageClass: 'STANDARD_IA',
        key: '页面1-5.png',
    }).then(res => {
        logResult('modifyStorageClass:', res);
    })
}


//获取文件文件的权限
function getObjectAcl(){
    ks3.getObjectAcl({
        key: '57M.pdf'
    }).then(res => {
        logResult('getObjectAcl:', res);
    })
}

//修改文件文件的权限
function putObjectAcl(){
    ks3.putObjectAcl({
        key: '57M.pdf',
        acl: 'private',
        bucket: 'xxx',
        region: 'BEIJING'
    }).then(res => {
        logResult('putObjectAcl:', res);
    })
}

function uploadFile(){
    ks3.uploadFile({
        key: 'test.txt',
        body: 'this is content', 
        headers: {}
    }, function(res){
        console.log(res)
        logResult('uploadFile:', res);
    })
}

function initPage(){
    var buttons = [
        'getObjectUrl',
        'listObjects',
        'headObject',
        'getObject',
        'putObject',
        'appendObject',
        'delObject',
        'restoreObject',
        'putObjectCopy',
        'uploadPartCopy-大文件分块复制',
        'uploadMultiPart-本地文件分块上传',
        'listParts-查询已上传块',
        'abortMultipartUpload-取消已上传块',
        'listMultipartUploads-查询正在进行的分块上传',
        'getObjectPartUploads-查询object下的正在上传的分块',
        'modifyStorageClass',
        'putObjectAcl',
        'getObjectAcl',
        'uploadFile'
    ];
    var container = document.querySelector('.main');
    var html = '';
    buttons.forEach(function(name){
        html+=`<button data-method='${name.match(/[a-zA-Z]+/g)[0]}'>${name}</button>`;
    })
    container.innerHTML = html;
    container.onclick = function (e) {
        if (e.target.tagName === 'BUTTON') {
            var name = e.target.getAttribute('data-method').trim();
            window[name]();
        }
    };
}


